import json
import time
from apps.coffee.models import coffee
from apps.coffee.serializers.coffee_serializer import CoffeeDetailSerializer, CoffeeSerializer
from utils.response import ApiResponse
from rest_framework.views import APIView
from django.utils.html import strip_tags
from django.utils.text import Truncator
from django.utils.safestring import mark_safe
from utils.custom_pagination import CustomPagination
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from apps.coffee.models import category as category_model

@method_decorator(csrf_exempt, name='dispatch')
class CoffeeView(APIView):
    serializer_class = CoffeeSerializer
    
    def get(self, request):
        """
        获取咖啡品类列表
        """
        queryset = coffee.objects.all()

        keywords = request.GET.get('keywords','')
        sort_field = request.GET.get('sort','-id')
        user_id= request.GET.get('user_id',None)
        category_id = request.GET.get('category',[])

        filters = {}

        if keywords:
            filters['title__icontains'] = keywords
        if user_id is not None:
            if isinstance(user_id, str) and user_id.isdigit():
                user_id_int = int(user_id)
                if user_id_int > 0:
                    filters['user_id'] = user_id_int
                else:
                    pass
        if category_id and category_id != '0':
            ids = category_model.get_all_children_ids(category_id)
            if ids:
                filters['category_id__in'] = ids
            else:
                filters['category_id'] = category_id
        #print(filters)
        # 应用过滤和排序
        queryset = queryset.filter(**filters).order_by(sort_field)
        # 创建分页器实例
        paginator = CustomPagination()
        
        # 分页查询集
        page = paginator.paginate_queryset(queryset, request)
        
        if page is not None:
            # 序列化分页数据
            serializer = self.serializer_class(page, many=True)
            # 获取分页响应
            return ApiResponse(
                code=200,
                message='success',
                data=paginator.get_paginated_response(serializer.data)
            )
        
        # 如果没有分页（page为None），返回所有数据
        serializer = self.serializer_class(queryset, many=True)
        return ApiResponse(
            code=200,
            message='获取成功',
            data=serializer.data
        )
    def detail(request,pk):
        try:
            # Get the model instance
            coffee_instance = coffee.objects.get(pk=pk)
            # Pass the model instance to the serializer
            serializer = CoffeeDetailSerializer(coffee_instance)
            return ApiResponse(code=200, message='详情获取成功', data=serializer.data)
        except coffee.DoesNotExist:
            return ApiResponse(code=404, message='数据不存在')
        except Exception as e:
            return ApiResponse(code=400, message=str(e))
    '''
        创建咖啡品类
    '''
    def post(self, request):
        try:
            data = self.make_data(request.data)
            data['create_time'] = time.time()
            data['update_time'] = time.time()
            coffee.objects.create(**request.data)
            return ApiResponse(code=200, message='添加成功')
        except Exception as e:
            return ApiResponse(code=400, message=str(e))
        
    def put(self, request, pk):
        try:
            #过滤非字段内容
            data = self.filter_data(request.data)
            #重构提交数据格式
            data = self.make_data(request.data)
            #刷新更新实践
            data['update_time'] = time.time()
            coffee.objects.filter(id=pk).update(**request.data)
            return ApiResponse(code=200, message='更新成功')
        except Exception as e:
            return ApiResponse(code=400, message=str(e))
    
    # 更改显示状态
    def change_status(request, pk):
        try: 
           
            data = coffee.objects.get(id=pk)
            message = '已成功关闭访问！' if data.status == 1 else '已成功开启访问！' 
            coffee.objects.filter(id=pk).update(status=0 if data.status == 1 else 1)
            return ApiResponse(code=200, message=message)
        except Exception as e:
            return ApiResponse(code=400, message=str(e))
    # 更改推荐状态
    def change_recommend(request, pk):
        try: 
           
            data = coffee.objects.get(id=pk)
            message = '已成功取消推荐！' if data.recommend == 1 else '已成功推荐！' 
            coffee.objects.filter(id=pk).update(recommend=0 if data.recommend == 1 else 1)
            return ApiResponse(code=200, message=message)
        except Exception as e:
            return ApiResponse(code=400, message=str(e))

    def delete(self, request, pk):
        try:
            coffee.objects.filter(id=pk).delete()
            return ApiResponse(code=200, message='删除成功')
        except Exception as e:
            return ApiResponse(code=400, message=str(e))


    def make_data(self, data):
        data['title'] = strip_tags(data.get('title'))

        # 描述
        if data.get('description'):
            data['description'] = strip_tags(data.get('description'))

        # 没有描述则截取内容
        if not data.get('description') and data.get('content'):
            data['description'] = self.truncator_text(data.get('content'), 120)

        # 富文本转义
        if data.get('content'):
            data['content'] = mark_safe(data.get('content'))

        if data.get('fields'):
            data['fields'] = json.dumps(data.get('fields'))

        if data.get('gallery'):
            data['gallery'] = json.dumps(data.get('gallery'))
            
        if data.get('category'):
            data['category'] = json.dumps(data.get('category'))
            
        return data

    def truncator_text(self, text, nums=50):
        plain_text = strip_tags(text)
        clear_plain_text = ' '.join(plain_text.split())
        return Truncator(clear_plain_text).chars(nums, truncate='...')
    def filter_data(self,data):
        # 定义咖啡模型的有效字段列表
        coffee_fields = ['id', 'title', 'category_id', 'cover', 'gallery', 'user_id', 'description', 'content', 'fields', 'update_time', 'views', 'likes', 'status', 'category', 'template']
        # 收集需要删除的键
        keys_to_remove = [key for key in data.keys() if key not in coffee_fields]
        # 遍历需要删除的键并从字典中移除它们
        for key in keys_to_remove:
            data.pop(key)
        return data